package com.youlu.campus.admin.auth.shiro.filter;

import com.alibaba.fastjson.JSON;
import com.youlu.campus.admin.auth.entity.exception.AuthErrorCode;
import com.youlu.campus.common.exception.ApiErrorCode;
import com.youlu.campus.common.base.RestResultBuilder;
import org.apache.commons.codec.CharEncoding;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * Created by zhuhuaiqi
 * <p>
 * //AuthorizationInfo
 * <p>
 * AuthorizationFilter
 *
 */
public class UriPermissionsFilter extends PermissionsAuthorizationFilter {

    protected final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object
            mappedValue) throws IOException {
        //logger.debug("isAccessAllowed mappedValue:{}", JSON.toJSONString(mappedValue));
        Subject subject = getSubject(request, response);

       /* String[] perms = (String[]) mappedValue;
        logger.debug("isAccessAllowed perms:{}", JSON.toJSONString(perms));*/

        //logger.debug("subject session:{}", JSON.toJSONString(subject.getSession()));

        String uri = getPathWithinApplication(request);

        logger.debug("UriPermissionsFilter.isAccessAllowed uri:{} authenticated:{}", uri,
                subject.isAuthenticated());

        if (!subject.isAuthenticated()) {
            logger.warn("UriPermissionsFilter.isAccessAllowed false, uri:{}", uri);
            return false;
        }

        boolean isPermitted = false;
        isPermitted = subject.isPermitted(uri);
        logger.info("UriPermissionsFilter.isAccessAllowed uri:{}, isPermitted:{}", uri, isPermitted);
        return isPermitted;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws
            IOException {
        outJson(response, AuthErrorCode.UNAUTHORIZED);
        return false;
    }

    /**
     * 使用 response 输出JSON
     *
     * @param response
     * @param errorCode
     * @throws IOException
     */
    public void outJson(ServletResponse response, ApiErrorCode errorCode) {
        PrintWriter out = null;
        try {
            response.setCharacterEncoding(CharEncoding.UTF_8);//设置编码
            response.setContentType("application/json; charset=utf-8");//设置返回类型
            out = response.getWriter();
            out.println(JSON.toJSONString(RestResultBuilder.builder().errorCode(errorCode).build()));//输出
        } catch (Exception e) {
            logger.error("json out error:{}", e.getMessage());
        } finally {
            if (null != out) {
                out.flush();
                out.close();
            }
        }
    }
}
